package com.itboye.ihomebank.adapter;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Created by itboye on 2017/2/20.
 */

public class ViewHouder {
    /**
     * View容器，用于存放Holer中的View 的SparseArray
     * 是Android推荐使用的一个优化容器，相当于一个Map<integer,View>
     */
    private SparseArray<View> mViews;

    /**
     * Item布局View convertView
     */
    private View mConvertView;

    public ViewHouder(Context context, ViewGroup parent, int layoutId) {
        mViews = new SparseArray<View>();
        mConvertView = LayoutInflater.from(context).inflate(layoutId, null);
        mConvertView.setTag(this);
    }

    /**
     * 获取ViewHolder
     *
     * @param context
     *            上下文
     * @param convertView
     * @param parent
     * @param layoutId
     *            布局layout Id
     * @param
     * @return
     */
    public static ViewHouder getViewHolder(Context context, View convertView,
                                           ViewGroup parent, int layoutId) {

        if (convertView == null)
            return new ViewHouder(context, parent, layoutId);
        return (ViewHouder) convertView.getTag();
    }

    /**
     *
     * 获取Holder中的ItemView
     *
     * @param viewId
     * @return
     */
    @SuppressWarnings("unchecked")
    public <T extends View> T getView(int viewId) {

        View item = mViews.get(viewId);
        if (item == null) {
            item = mConvertView.findViewById(viewId);
            mViews.put(viewId, item);
        }
        return (T) item;
    }

    /**
     * 设置TextView 的文本
     *
     * @param viewId
     * @param text
     */
    public TextView setTVText(int viewId, String text) {
        TextView tv = getView(viewId);
        tv.setText(text);
        return tv;
    }
    public TextView setsetBackground(int viewId,int color){

        TextView tv=getView(viewId);
        return tv;
    }

    /**
     * 设置EditText 的文本
     *
     * @param viewId
     * @param text
     */
    public EditText setETText(int viewId, String text) {
        EditText et = getView(viewId);
        et.setText(text);
        return et;
    }

    /**
     * 设置TextView 的文本
     *
     * @param viewId
    //     * @param text
     */
    public ImageView setIVBg(int viewId, int imgId) {
        ImageView iv = getView(viewId);
        iv.setImageResource(imgId);
        return iv;
    }

    /**
     * 设置TextView 的文本
     *
     * @param viewId
     * @param text
     */
    public void setTextView(int viewId, String text) {
        TextView tv = getView(viewId);
        tv.setText(text);
    }

    /**
     * 获取convertView
     *
     * @return
     */
    public View getMConvertView() {
        return mConvertView;
    }
}
